// SKNotes - a note taking and gathering tool
// Copyright (C) 2009  Stefan Kueng
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

namespace SKNotes.Configuration
{
    using System;

	public class ValueSetting : ValueSettingBase
	{

		public ValueSetting( string name, Type valueType ) :
			this( name, valueType, null, null )
		{
		}

		public ValueSetting( string name, Type valueType, object value ) :
			this( name, valueType, value, null )
		{
		}

		public ValueSetting( string name, Type valueType, object value, object defaultValue ) :
			base( name, defaultValue )
		{
			if ( valueType == null )
			{
				throw new ArgumentNullException( "valueType" );
			}
			if ( defaultValue != null && !defaultValue.GetType().Equals( valueType ) )
			{
				throw new ArgumentException( "defaultValue" );
			}

			this.valueType = valueType;
			ChangeValue( value );
		} 

		public override object OriginalValue
		{
			get { return LoadValue( Name, this.valueType, SerializeAs, DefaultValue ); }
		}

		public override object Value
		{
			get { return this.value; }
			set { ChangeValue( value ); }
		} 

		public override void Load()
		{
			try
			{
				object originalValue = OriginalValue;
				if ( originalValue == null && LoadUndefinedValue == false )
				{
					return;
				}
				Value = originalValue;
			}
			catch
			{
				if ( ThrowOnErrorLoading )
				{
					throw;
				}
			}
		}

		public override void Save()
		{
			try
			{
				object toSaveValue = Value;
				if ( toSaveValue == null && SaveUndefinedValue == false )
				{
					return;
				}
				SaveValue( Name, this.valueType, SerializeAs, toSaveValue, DefaultValue );
			}
			catch
			{
				if ( ThrowOnErrorSaving )
				{
					throw;
				}
			}
		}

		private void ChangeValue( object newValue )
		{
			if ( newValue != null && !newValue.GetType().Equals( this.valueType ) )
			{
				throw new ArgumentException( "newValue" );
			}
			this.value = newValue;
		}

		private readonly Type valueType;
		private object value;

	}
} 
